package com.oa.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.joneying.common.annotation.CommonService;
import com.joneying.common.web.response.Resp;
import com.oa.admin.dto.FixedAssetsAddDTO;
import com.oa.admin.dto.FixedAssetsConditionDTO;
import com.oa.admin.exportvo.FixedAssetsExportVO;
import com.oa.admin.vo.FixedAssetsDetailsVO;
import com.oa.admin.vo.FixedAssetsTypeVo;
import com.oa.admin.vo.FixedAssetsUpdateDTO;
import com.oa.admin.vo.FixedAssetsVO;
import com.oa.core.PageResult;
import com.oa.admin.entity.FixedAssets;
import com.oa.admin.mapper.FixedAssetsMapper;
import com.oa.admin.service.IFixedAssetsService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.oa.core.enumm.CodeEnum;
import com.oa.core.exception.BusinessException;
import com.oa.core.exception.DataIsEmptyException;
import com.oa.core.utils.DateUtil;
import com.oa.core.utils.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import static com.oa.core.utils.Validate.validate;

/**
 * <p>
 * 固定资产表 服务实现类
 * </p>
 *
 * @author syb123
 * @since 2019-01-22
 */
@Service
public class FixedAssetsServiceImpl extends ServiceImpl<FixedAssetsMapper, FixedAssets> implements IFixedAssetsService {

    private final FixedAssetsMapper fixedAssetsMapper;
    @Autowired
    private HttpServletResponse response;

    @Autowired
    public FixedAssetsServiceImpl(FixedAssetsMapper fixedAssetsMapper) {
        this.fixedAssetsMapper = fixedAssetsMapper;
    }

    @Override
    @CommonService
    public PageResult<FixedAssets> findList(Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            List<FixedAssets> list = fixedAssetsMapper.findList();
            return new PageResult<>(list);
        } else {
            // 当前页，总条数 构造 page 对象
            Page<FixedAssets> page = new Page<>(pageNum, pageSize);
            //查询
            List<FixedAssets> list = fixedAssetsMapper.findList(page);
            return new PageResult<>(list);
        }
    }

    /**
     * 根据id查询
     */
    @Override
    @CommonService
    public FixedAssets findFixedAssetsById(String id) {
        return fixedAssetsMapper.findById(id);
    }

    /**
     * 新增固定资产
     *
     * @param fixedAssetsAddDTO
     * @return
     */
    @Override
    @CommonService
    @Transactional
    public Resp addFixedAssets(FixedAssetsAddDTO fixedAssetsAddDTO) throws BusinessException {

        CheckoutParam(fixedAssetsAddDTO);//校验

        FixedAssets fixedAssets = new FixedAssets();
        BeanUtils.copyProperties(fixedAssetsAddDTO, fixedAssets);

        fixedAssets.setAssetsState(2);//默认资产状态
        try {
            insert(fixedAssets);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("添加资产失败!");
        }
        return new Resp<String>().success("添加资产成功!");
    }

    /**
     * 根据条件查询固定资产
     *
     * @param fixedAssetsConditionDTO
     * @return
     */
    @Override
    @CommonService
    public PageResult<FixedAssetsVO> findFixedAssetsListCondition(FixedAssetsConditionDTO fixedAssetsConditionDTO) throws DataIsEmptyException {

        if (fixedAssetsConditionDTO.getPage() == null) {

            List<FixedAssetsVO> fixedAssetsVOList = fixedAssetsMapper.findFixedAssetsListCondition(
                    fixedAssetsConditionDTO.getBuyTimeMin(),
                    fixedAssetsConditionDTO.getBuyTimeMax(),
                    fixedAssetsConditionDTO.getAssetsState(),
                    fixedAssetsConditionDTO.getStopTime(),
                    fixedAssetsConditionDTO.getAssetsName(),
                    fixedAssetsConditionDTO.getAssetsType(),
                    fixedAssetsConditionDTO.getDepartmentId(),
                    fixedAssetsConditionDTO.getUserName()
            );
            if (CollUtil.isEmpty(fixedAssetsVOList)) {
                throw new DataIsEmptyException();
            }
            return new PageResult<FixedAssetsVO>(fixedAssetsVOList);
        } else {

            Page<FixedAssets> page = new Page<>(fixedAssetsConditionDTO.getPage(), fixedAssetsConditionDTO.getLimit());
            List<FixedAssetsVO> fixedAssetsVOList = fixedAssetsMapper.findFixedAssetsListCondition(
                    page,
                    fixedAssetsConditionDTO.getBuyTimeMin(),
                    fixedAssetsConditionDTO.getBuyTimeMax(),
                    fixedAssetsConditionDTO.getAssetsState(),
                    fixedAssetsConditionDTO.getStopTime(),
                    fixedAssetsConditionDTO.getAssetsName(),
                    fixedAssetsConditionDTO.getAssetsType(),
                    fixedAssetsConditionDTO.getDepartmentId(),
                    fixedAssetsConditionDTO.getUserName()
            );
            if (CollUtil.isEmpty(fixedAssetsVOList)) {
                throw new DataIsEmptyException();
            }
            return new PageResult<FixedAssetsVO>(fixedAssetsVOList);
        }
    }

    /**
     * 查询资产类别
     *
     * @return
     */
    @Override
    @CommonService
    public Resp findFixedAssetsType() throws DataIsEmptyException {
        List<FixedAssetsTypeVo> fixedAssetsTypeVoList = fixedAssetsMapper.findFixedAssetsType();
        if (CollUtil.isEmpty(fixedAssetsTypeVoList)) {
            throw new DataIsEmptyException();
        }
        return new Resp<>().success(fixedAssetsTypeVoList);
    }

    /**
     * 根据主键id查询资产详情
     *
     * @param id
     * @return
     */
    @Override
    @CommonService
    public Resp findFixedAssetsDetailsById(String id) throws DataIsEmptyException {
        FixedAssetsDetailsVO fixedAssetsDetailsVO = fixedAssetsMapper.findFixedAssetsDetailsById(id);
        if (StringUtils.isEmpty(fixedAssetsDetailsVO)) {
            throw new DataIsEmptyException();
        }
        return new Resp<FixedAssetsDetailsVO>().success(fixedAssetsDetailsVO);
    }

    /**
     * 根据主键id修改资产
     *
     * @param fixedAssetsUpdateVO
     * @return
     */
    @Override
    @CommonService
    public Resp updateFixedAssetsById(FixedAssetsUpdateDTO fixedAssetsUpdateVO) throws BusinessException {
        FixedAssets fixedAssets = new FixedAssets();
        BeanUtils.copyProperties(fixedAssetsUpdateVO, fixedAssets);
        try {
            updateById(fixedAssets);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("修改资产失败!");
        }

        return new Resp<>().success("修改资产成功!");
    }

    /**
     * 根据主键id删除资产
     *
     * @param id
     * @return
     */
    @Override
    @CommonService
    public Resp deleteFixedAssets(String id) throws DataIsEmptyException, BusinessException {

        FixedAssets fixedAssets = selectById(id);

        if (StringUtils.isEmpty(fixedAssets)) {
            throw new DataIsEmptyException();
        }

        if ((!StringUtils.isEmpty(fixedAssets.getUserId())) || (!StringUtils.isEmpty(fixedAssets.getDepartmentId()))) {
            throw new BusinessException("该资产在使用中!");
        }

        fixedAssets.setIsDeleted(1);

        try {
            updateById(fixedAssets);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("删除资产失败!");
        }

        return new Resp<>().success("删除资产成功!");
    }

    /**
     * 导出资产列表
     *
     * @return
     */
    @Override
    @CommonService
    public Resp exportFixedAssetsList() throws BusinessException, DataIsEmptyException {

        List<FixedAssetsVO> fixedAssetsVOS = fixedAssetsMapper.
                findFixedAssetsListCondition(null, null, null, null, null, null, null, null);

        if (CollUtil.isNotEmpty(fixedAssetsVOS)) {
            List<FixedAssetsExportVO> fixedAssetsExportVOList = new ArrayList<>();
            fixedAssetsVOS.forEach(x -> {
                FixedAssetsExportVO fixedAssetsExportVO = new FixedAssetsExportVO();
                BeanUtils.copyProperties(x, fixedAssetsExportVO);
                fixedAssetsExportVOList.add(fixedAssetsExportVO);
            });

            String[] rowName = {"状态", "资产编码", "资产名称", "资产类别", "型号规格", "采购金额", "使用部门", "使用人员", "购入时间", "有效期", "备注"};


            try {
                ExcelUtil.downloadExcel("固定资产" + DateUtil.getDayMonth(), rowName, fixedAssetsExportVOList, "固定资产" + DateUtil.getDayMonth() + ".xls", response);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("导出固定资产excel表格失败!");
            }

            return new Resp<>().success("删除资产成功!");
        }

        //数据为空
        throw new DataIsEmptyException();
    }


    /**
     * 参数校验
     *
     * @param fixedAssetsAddDTO
     */
    public void CheckoutParam(FixedAssetsAddDTO fixedAssetsAddDTO) throws BusinessException {
        if (!StringUtils.isEmpty(fixedAssetsAddDTO)) {
            List<String> validate = validate(fixedAssetsAddDTO);
            if (CollUtil.isNotEmpty(validate)) {
                throw new BusinessException(CodeEnum.PARAMETERS_OF_THE_ABNORMAL.getCode(), validate.toString());
            }
        }
    }
}
